package com.da.lon.wang.xlg.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class NetUtil {

    private static final int TIMEOUT = 30000;

    private static final String TAG = NetUtil.class.getName();

    /**
     * HTTP 获取内容
     *
     * @param urlStr 服务器连接
     * @return null or {@link String}
     */
    public static String HttpGet(String urlStr) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        URL url;
        StringBuilder builder = new StringBuilder();
        String result = null;
        String sessionid = null;
        try {
            Thread.sleep(200L);
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            if (sessionid != null) {
                conn.setRequestProperty("cookie", sessionid);
            }
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            conn.setUseCaches(false);
            conn.connect();
            String cookieval = conn.getHeaderField("set-cookie");
            if (cookieval != null) {
                sessionid = cookieval.substring(0, cookieval.indexOf(";"));
            }
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            result = builder.toString();
            Log.i(TAG, "sessionid: " + urlStr + "\n服务器返回的内容: " + sessionid);
        } catch (InterruptedException e) {
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }

            if (conn != null) {
                conn.disconnect();
            }
        }

        return result;
    }
}
